-- ======================================================================
-- Hell Lua Bus
-- 
-- Copyright 2012-2014 Hell-Prototypes
--
-- http://www.hellprototypes.com/
--
-- This is free software, licensed under the terms of the GNU General
-- Public License as published by the Free Software Foundation.
-- ======================================================================
iHEX = require "mod_iHEX"
CRC= require "mod_crc16"
printf= require "mod_print"

function connect_table(to, from)
    local ret = to
    local index = #ret + 1
    for i=1, #from do
        ret[index] = from[i]
        index = index + 1
    end
    
    return ret
end

function convert_uint16_to_array(uint16)
	local array = {}
	array[1] = bit32.band(uint16, 0xFF)
	array[2] = bit32.band(bit32.rshift(uint16, 8),  0xFF)
	return array
end

local hex_file = arg[1]

if hex_file == nil then
	print("Error: Need HEX file name")
	return
end

print("========================================")
print("iHex File: " .. hex_file)
print("========================================")


local image_crc = 0
local pgm_start_addr, pgm_raw_data = iHEX.Read_File(hex_file)
if type(pgm_raw_data) == "table" then
	--printf.table(pgm_raw_data)
	print(string.format("\r\nFW start address = 0x%04x, size = %d", pgm_start_addr, #pgm_raw_data))

	image_crc = CRC.crc16_ccitt(pgm_raw_data, #pgm_raw_data)

	print(string.format("Image CRC = 0x%04x ", image_crc))
else
	print("Error: fail to read hex file.")
	return
end

local init_packet = {}

local hardware_version = {0xFF, 0xFF}
local hardware_revision = {0xFF, 0xFF}
local application_version = {0xFF, 0xFF, 0xFF, 0xFF}
local softdevice_len = {0x01, 0x00}
local softdevice_array = {0xFE, 0xFF}
local crc_array = convert_uint16_to_array(image_crc)

connect_table(init_packet,hardware_version)
connect_table(init_packet,hardware_revision)
connect_table(init_packet,application_version)
connect_table(init_packet,softdevice_len)
connect_table(init_packet,softdevice_array)
connect_table(init_packet,crc_array)

printf.table(init_packet)

local dat_file = string.sub(hex_file, 1, string.len(hex_file)-4) .. "_ext_init.dat"
print("DAT File: " .. dat_file)

local file_w = io.open(dat_file, "wb")
for i = 1, #init_packet do
	file_w:write(string.char(init_packet[i]))
end
file_w:close()